import axios from 'axios'
import store from '../store'
import config from './config-client'
import {cookie} from '@utils'
axios.interceptors.request.use(config => {
  store.dispatch('global/gProgress', 50)
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => response, error => Promise.resolve(error.response))

function checkStatus(response) {
  store.dispatch('global/gProgress', 100)
  if (response.status === 200 || response.status === 304) {
    return response
  }
  return {
    data: {
      code: -404,
      message: response.statusText,
      data: ''
    }
  }
}

function checkCode(res) {
  // if (res.status === -500) {
  //   window.location.href = '/backend'
  // } else if (res.status === -400) {
  //   window.location.href = '/'
  // } else if (res.status !== 200) {
  //   store.dispatch('global/showMsg', res.data.message)
  // }
  return res
}

export default {
  post(url, data) {
    return axios({
      method: 'post',
      url: config.api + url,
      data,
      timeout: config.timeout,
      headers: {
        'Content-Type': 'application/json;charset=utf-8',
        'token': cookie('SHOP_TOKEN') || ''
      }
    }).then(checkStatus).then(checkCode)
  },
  get(url, params) {
    return axios({
      method: 'get',
      url: config.api + url,
      params,
      timeout: config.timeout,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'token': cookie('SHOP_TOKEN') || ''
      }
    }).then(checkStatus).then(checkCode)
  }
}
